<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class cursos extends CI_Controller {
	
	public function __construct()
	{
		parent::__construct();
		$this->load->model('cursos_model');
		$this->load->library('session');
		$this->load->library('email');
		$this->load->library('tank_auth');
		$this->load->helper('url');
		$this->load->helper('form');
		$this->load->helper('date');
	}
	
	public function index()
	{
		$data['title'] = 'Plan de cursos - Starscamp';
		$data['result'] = $this->cursos_model->get_published();
		foreach($data['result'] as $row)
		{
			$row->price = $row->price ? 'Valor S/. '.$row->price : 'GRATIS';
			$row->event_date = $this->_format_date($row->event_date);
		}
		
		$this->load->view('templates/header', $data);
		$this->load->view('cursos', $data);
		$this->load->view('templates/footer', $data);
	}
	
	public function detalle($id = FALSE)
	{
		// validate id
		if(!$this->cursos_model->get_id_published($id))
		{
			// if no session, cancel preview
			if(!$this->tank_auth->is_logged_in())
			{
				show_404();
			}
		}
		
		if($this->session->flashdata('message'))
		{
			$data['message'] = $this->session->flashdata('message');
		}
								
		// This method will have the credentials validation
		$this->load->library('form_validation');
		$this->load->helper('captcha');	 // captcha
		$this->form_validation->set_rules('name', 'Nombres', 'trim|required|xss_clean|callback_check_full['.$id.']');
		$this->form_validation->set_rules('lname', 'Apellidos', 'trim|required|xss_clean');
		$this->form_validation->set_rules('dni', 'Documento de identidad', 'trim|required|xss_clean|exact_length[8]|callback_check_repeat['.$id.']');
		$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email');
		$this->form_validation->set_rules('cel', 'Celular', 'trim|required|xss_clean|numeric|min_length[9]|max_length[12]');
		$this->form_validation->set_rules('captcha', 'Captcha', 'callback_validate_captcha'); // captcha
		
		if($this->form_validation->run())
		{
			$input = $this->input->post();
			$input['id_evento'] = $id;
			$this->cursos_model->insert_inscritos($input);
			$this->_send_email($id, $input);		
			$this->session->unset_userdata('captcha_cursos'); // captcha
			$this->session->set_flashdata('message', 'Se han enviado tus datos exitosamente');
			redirect('cursos/detalle/'.$id, 'refresh');
		}
		
		$word = array_merge(range(0,9), range('a','z'), range('A', 'Z'));
		$word = implode('', $word);
		$word = substr(str_shuffle($word), 0, 4);
		$cap = create_captcha(array('word'=>$word, 'img_path'=>'./assets/captcha/', 'img_url'=>base_url().'assets/captcha/', 'font_path'=>'./assets/font/2.ttf'));
		$this->session->set_userdata(array('captcha_cursos'=>$cap['word']));
		
		$data['title'] = 'Plan de cursos - Starscamp';
		$data['row'] = $this->cursos_model->get_id($id);
		$data['row']->price = $data['row']->price ? 'Valor S/. '.$data['row']->price : 'GRATIS';
		$data['row']->formatted_date = $this->_format_date($data['row']->event_date);
		$data['captcha'] = $cap['image']; // captcha
		$this->load->view('templates/header', $data);
		$this->load->view('cursos-detalle', $data);
		$this->load->view('templates/footer', $data);
	}
	
	public function validate_captcha($captcha){
		if($captcha === $this->session->userdata['captcha_cursos'])
		{
			return TRUE;
		}
		else
		{
			$this->form_validation->set_message('validate_captcha', 'El código captcha es incorrecto');
			return FALSE;
		}
	}
	
	public function check_full($null, $id_evento)
	{
		// query the database
		$row = $this->cursos_model->get_id($id_evento);
		if($row->filled < $row->vacants)
		{
			return TRUE;
		}
		else
		{
			$this->form_validation->set_message('check_full', 'Lo sentimos, ya no hay vacantes disponibles');
			return FALSE;
		}
	}
	
	public function check_repeat($dni, $id_evento)
	{		
		// query the database
		$result = $this->cursos_model->check_inscritos($id_evento, $dni);
		
		if(!$result)
		{
			return TRUE;
		}
		else
		{
			$this->form_validation->set_message('check_repeat', 'Usted ya se encuentra registrado en este evento');
			return FALSE;
		}
	}
	
	private function _format_date($str)
	{
		$weekday = str_replace(
			array('6', '5', '4', '3', '2', '1', '0'),
			array('Sábado', 'Viernes', 'Jueves', 'Miércoles', 'Martes', 'Lunes'),
			mdate('%w', strtotime($str))
		);
		
		$day = mdate('%d', strtotime($str));
		
		$month = str_replace(
			array('12', '11', '10', '09', '08', '07', '06', '05', '04', '03', '02', '01'),
			array('diciembre', 'noviembre', 'octubre', 'septiembre', 'agosto', 'julio', 'junio', 'mayo', 'abril', 'marzo', 'febrero', 'enero'),
			mdate('%m', strtotime($str))
		);
		
		return $weekday.' '.$day.' de '.$month;
	}
	
	private function _send_email($id_evento, $input)
	{
		$evento = $this->cursos_model->get_id($id_evento);
		
		// initialize email
		$this->email->initialize(array('mailtype'=>'html'));
		
		// email admin		
		$this->email->clear();
		$this->email->from('noreply@starscamp.net', 'Starscamp');
		$this->email->to('info@starscamp.net');
		
		$this->email->subject('Inscripción - '.$evento->name);
		$this->email->message('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
		<html xmlns="http://www.w3.org/1999/xhtml">
		<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>Formulario de contacto</title>
		</head>
		
		  <body>
				            <table align=center width=100% style="padding:20px;" >
		<tr><td>
		<table align=center width=560 style="font-family:sans-serif; color:#FFF; background-color:#335259;">         
		<tr><td colspan=3 height=20></td></tr>        
        <tr>
        	<td width=20></td>
			<td><p><img src="http://starscamp.net/img/logo.png" alt=Starscamp></p>
		<h2 style="color:#fff;">Inscripción para: '.$evento->name.'</h2>
			<p><strong style="color:#fff;">'.$this->_format_date($evento->event_date).' - '.$evento->time.'</strong></p>
			<p><strong style="color:#fff;"> Nombres:</strong> '.$input['name'].'</p>
			<p><strong style="color:#fff;">Apellidos:</strong> '.$input['lname'].'</p>
			<p><strong style="color:#fff;">DNI:</strong> '.$input['dni'].'</p>
			<p><strong style="color:#fff;">Teléfono:</strong> '.$input['cel'].'</p>
			<p><strong style="color:#fff;">Email:<strong> <a style="color:#FFF"; href="mailto:'.$input['email'].'">'.$input['email'].'</a></p>
            </td>
            <td width=20></td>
       </tr>       
       <tr><td colspan=3 height=20></td></tr>        
		</table>	
		</td></tr>
		</table>
		</body>
		<html>');
		
		$this->email->send();
		
		// email cliente
		$this->email->clear();
		$this->email->from('info@starscamp.net', 'Starscamp');
		$this->email->to($input['email']);
		
		$this->email->subject('Inscripción - '.$evento->name);
		$this->email->message('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
		<html xmlns="http://www.w3.org/1999/xhtml">
		<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>Formulario de contacto</title>
		</head>
		
		<body>
			            <table align=center width=100% style="padding:20px;" >
		<tr><td>
		<table align=center width=560 style="font-family:sans-serif; color:#FFF; background-color:#335259;">         
		<tr><td colspan=3 height=20></td></tr>        
        <tr>
        	<td width=20></td>
			<td><p><img src="http://starscamp.net/img/logo.png" alt=Starscamp></p>
			
			<h2 style="color:#fff;">Hola '.$input['name'].'</h2>
			<p style="color:#fff;">
				Te has inscrito a: <strong>'.$evento->name.'</strong><br>
                Horario: <strong>'.$this->_format_date($evento->event_date).' - '.$evento->time.'</strong>
			</p>
			<p style="color:#fff;">
				Gracias por inscribirte, muy pronto
				nos pondremos en contacto contigo
				para confirmar tu asistencia al evento.
			</p>
			<p style="color:#fff;">
				General Trinidad Morán 990 - Lince. Lima-Perú.<br>
				T/ (01) 624 1608
			</p>
            </td>
            <td width=20></td>
       </tr>       
       <tr><td colspan=3 height=20></td></tr>        
		</table>	
		</td></tr>
		</table>
		</body>
		<html>');
		
		$this->email->send();
	}
}

/* End of file cursos.php */
/* Location: ./application/controllers/cursos.php */